import 'dart:convert';
import 'dart:io';
import 'package:ceramics/extensions/ab_list_extensions.dart';
import 'package:ceramics/model/ab_like.dart';
import 'package:ceramics/model/ab_oauth.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

import '../util/empty.dart';
import 'ab_block.dart';

class ABSingleton {
  static final ABSingleton _singleton = ABSingleton._internal();

  factory ABSingleton() {
    return _singleton;
  }

  ABSingleton._internal();

  ABOAuthResponse? oauth;
  static ABUser? get user => _singleton.oauth?.userInfo;
  List<ABUser> users = [];
  static var follows = <ABUser>[].obs;
  static var likes = <ABLike>[].obs;
  static var blocks = <ABBlock>[].obs;

  static bool get isLogin => !isNullOrEmpty(ABSingleton().oauth?.token);
  static String? get token => ABSingleton().oauth?.token;

  static bool didFollow(String userId) {
    var didFollowed = follows.containsWhere((element) => element.userId == userId);
    return didFollowed;
  }

  static bool didLike(String likeId) {
    return likes.containsWhere((element) => element.likeId == likeId);
  }

  static updateFollows() async {
    await api.followList(10000, 1);
  }

  static fetchConfig() async {
    await api.fetchConfig();
  }

  static updateOAuth(ABOAuthResponse user) async {
    _singleton.oauth = user;
    await saveOAuth();
  }

  static saveOAuth() async {
    var docPath = await getApplicationDocumentsDirectory();
    var file = File("${docPath.path}/oauth.json");
    var userMap = _singleton.oauth?.toJson();
    var userMapString = jsonEncode(userMap);
    file.writeAsString(userMapString);
  }

  static removeOAuth() async {
    var docPath = await getApplicationDocumentsDirectory();
    var file = File("${docPath.path}/oauth.json");
    file.deleteSync();
    _singleton.oauth = null;
  }

  static initUser() async {
    var docPath = await getApplicationDocumentsDirectory();
    var file = File("${docPath.path}/oauth.json");
    if (file.existsSync()) {
      var userMapString = file.readAsStringSync();
      var userMap = jsonDecode(userMapString);
      _singleton.oauth = ABOAuthResponse.fromJson(userMap);
    }
  }




}